package seo.dale.util.datastructure;

public class ArrayBasedCapacityFixedQueue<E> implements Queue<E> {

	private Object[] array;
	
	private int size;
	private int head;
	private int tail;
	
	public ArrayBasedCapacityFixedQueue(int capacity) {
		array = new Object[capacity];
		head = 0;
		tail = 0;
	}
	
	@Override
	public E add(E item) {
		if (isFull()) {
			throw new RuntimeException("Queue is full.");
		}
		size++;
		array[tail] = item;
		tail = inc(tail);
		return item;
	}

	@Override
	@SuppressWarnings("unchecked")
	public E element() {
		if (isEmpty()) {
			throw new RuntimeException("Queue is empty.");
		}
		return (E) array[head];
	}

	@Override
	public E remove() {
		E item = element();
		array[head] = null;
		head = inc(head);
		size--;
		return item;
	}
	
	@Override
	public boolean isEmpty() {
		return size == 0;
	}
	
	private boolean isFull() {
		return size == array.length;
	}
	
	private int inc(int i) {
		return ++i == array.length ? 0 : i;
	}

}
